package com.heiyu.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import com.heiyu.api.request.CoinPairGetRequest;
import com.heiyu.api.request.CoinPairLineListRequest;
import com.heiyu.api.response.CoinPairGetResponse;
import com.heiyu.api.response.CoinPairLineResponse;
import com.heiyu.api.response.model.CoinPairLineModel;
import com.heiyu.api.response.model.CoinPairModel;
import com.heiyu.api.response.model.PointInfo;
import com.heiyu.controller.ApiBaseController;
import com.heiyu.dao.*;
import com.heiyu.entity.*;
import com.heiyu.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by mountain on 18/6/11.
 */
@Api(value = "交易对相关",description = "交易对行情相关")
@RestController
@RequestMapping("api/v1/coin/trade/price")
public class CoinTradePriceController extends ApiBaseController{

    @Autowired
    private ShowInfoMapper showInfoMapper;
    @Autowired
    private UserFollowMapper userFollowMapper;
    @Autowired
    private ShowFull5minMapper showFull5mMapper;
    @Autowired
    private MarketCoinCoinMapper coinCoinMapper;
    @Value("${kline.path}")
    private String klinePath;

    @ApiOperation(value="get",notes = "获取交易对详情")
    @RequestMapping(value = "get",method = RequestMethod.GET)
    public CoinPairGetResponse get(@ModelAttribute CoinPairGetRequest request){
        UserInfo userInfo = getUser();
        CoinPairGetResponse response = new CoinPairGetResponse();
        ShowInfo showInfo = this.showInfoMapper.selectPrimary(Long.valueOf(request.getTargetId()));
        if(showInfo==null){
            response.error("交易对信息不存在");
        }else{
            CoinPairModel model = new CoinPairModel();
            model.setMaxPirce(MoneyUtils.formatterCoin(showInfo.getHigh1d()));
            model.setMinPrice(MoneyUtils.formatterCoin(showInfo.getLow1d()));
            model.setCoinName(showInfo.getSymbol());
            if(defaultSymbol()){
                model.setPrice(MoneyUtils.formatter(showInfo.getPriceCny(),false));
                model.setDiffPrice(RangeUtil.diffPrice(showInfo.getPriceCny(),showInfo.getPercentChange24h()));
                model.setTradeAmount(MoneyUtils.formatter(showInfo.getVol24hCny(),true));
            }else{
                model.setPrice(MoneyUtils.formatter(showInfo.getPriceUsd(),false));
                model.setDiffPrice(RangeUtil.diffPrice(showInfo.getPriceUsd(),showInfo.getPercentChange24h()));
                model.setTradeAmount(MoneyUtils.formatter(showInfo.getVol24hUsd(),true));
            }

            model.setClosePrice(MoneyUtils.formatterCoin(showInfo.getPriceNative()));
            model.setOpenPrice(MoneyUtils.formatterCoin(showInfo.getOpenPriceNative()));
            model.setExchangeCoinName(showInfo.getTCoin());
            model.setRange(RangeUtil.formatter(showInfo.getPercentChange24h()));

            model.setName(showInfo.getMarketName());
            if(userInfo != null){
                UserFollow follow  = new UserFollow();
                follow.setFCoin(showInfo.getId()+"");
                follow.setUserName(userInfo.getTelphone());
                try{
                    follow = this.userFollowMapper.selectList(follow).get(0);
                    model.setCollectId(follow.getId());
                }catch (Exception e){

                }
            }
            response.success();
            response.setData(model);
        }
        return response;
    }

    @ApiOperation(value="line/list",notes = "获取交易对K线数据")
    @RequestMapping(value = "line/list",method = RequestMethod.GET)
    public CoinPairLineResponse lineList(@ModelAttribute CoinPairLineListRequest request){
        CoinPairLineResponse response = new CoinPairLineResponse();
        response.success();
        ShowInfo showInfo = showInfoMapper.selectPrimary(Long.valueOf(request.getTargetId()));
        if(showInfo == null){
            response.error("币对信息不存在");
        }else{
            if(request.getPageIndex()==null){
                request.setPageIndex(1);
            }
            response.setData(new CoinPairLineModel());
            MarketCoinCoin coinCoin = new MarketCoinCoin();
            coinCoin.setFCoin(showInfo.getSymbol());
            coinCoin.setTCoin(showInfo.getTCoin());
            if(showInfo.getMarketName().indexOf(".")>=0){
                coinCoin.setMarketName(showInfo.getMarketName().replace(".",""));
            }else{
                coinCoin.setMarketName(showInfo.getMarketName());
            }
            List<MarketCoinCoin> list = this.coinCoinMapper.selectList(coinCoin);
            if(request.getTimeType().equals("0")){
                response.getData().setList(get5MinKLine(showInfo,request.getPageIndex()));
            }else if(CollectionUtils.isEmpty(list)){
                response.getData().setList(get5MinKLine(showInfo,request.getPageIndex()));
            }else{
                response.getData().setList(getKLine(showInfo,request.getTimeType(),request.getPageIndex()));
            }
        }
        return response;
    }


    private List<PointInfo> get5MinKLine(ShowInfo showInfo,Integer pageIndex){
            Integer pageSize = 264;
            Map<String,Object> param = PageUtils.newParam(pageIndex,pageSize);
            param.put("symbol",showInfo.getSymbol());
            param.put("tCoin",showInfo.getTCoin());
            param.put("marketName",showInfo.getMarketName());
            List<ShowFull5min> list = this.showFull5mMapper.selectForKline(param);
            List<PointInfo> result = Lists.newArrayList();
            PointInfo pointInfo;
            for(ShowFull5min info:list){
                pointInfo = new PointInfo();
                pointInfo.setDateTime(DateUtils.format(info.getCreateTime(),"yyyy/MM/dd HH:mm"));
                if(defaultSymbol()){
                    pointInfo.setPrice(MoneyUtils.formatterCoin(info.getPriceCny()));
                    pointInfo.setMaxPrice(MoneyUtils.formatterCoin(info.getPriceCny()));
                    pointInfo.setMinPrice(MoneyUtils.formatterCoin(info.getPriceCny()));
                    pointInfo.setTradeAmount(MoneyUtils.formatterCoin(info.getVol24hCny()));
                }else{
                    pointInfo.setPrice(MoneyUtils.formatterCoin(info.getPriceUsd()));
                    pointInfo.setMaxPrice(MoneyUtils.formatterCoin(info.getPriceUsd()));
                    pointInfo.setMinPrice(MoneyUtils.formatterCoin(info.getPriceUsd()));
                    pointInfo.setTradeAmount(MoneyUtils.formatterCoin(info.getVol24hUsd()));
                }
                pointInfo.setTimestamp(Integer.valueOf(info.getCreateTime().getTime()/1000+""));
                result.add(pointInfo);
            }
            return Lists.reverse(result);
    }

    private List<PointInfo> getKLine(ShowInfo showInfo,String type,Integer pageIndex){
        List<PointInfo> list = Lists.newArrayList();
        if(StringUtils.isEmpty(type)){
            type = "1";
        }
        PointInfo info;
        String obj;
        switch (type){
            case "0":
                break;
            case "1":
                Date targetDate = DateUtils.getTargetDate(new Date(),1-pageIndex);
               obj =  FileUtils.read(klinePath+(showInfo.getMarketName().indexOf(".")>=0?showInfo.getMarketName().replace(".","").toLowerCase():showInfo.getMarketName().toLowerCase())
                        +"/"+showInfo.getSymbol()+"_"+showInfo.getTCoin()+"/"+DateUtils.format(targetDate,"yyyyMM")+"/"+DateUtils.format(targetDate,"yyyyMMdd")+"_5m.json");
               if(obj != null){
                   obj = "["+obj.replaceAll("\n",",")+"]";
                   JSONArray dayData = JSONArray.parseArray(obj);
                   JSONArray line;
                   for(int i=0;i<dayData.size();i++){
                       line =JSONArray.parseArray(dayData.get(i).toString());
                        info = new PointInfo();
                        info.setDateTime(DateUtils.format(new Date(Long.valueOf(line.get(0).toString())),"yyyy/MM/dd HH:mm"));
                        info.setTimestamp(DateUtils.getTimestamp(line.get(0).toString()));
                        info.setOpenPrice(line.get(1).toString());
                        info.setClosePirce(line.get(2).toString());
                        info.setMinPrice(line.get(3).toString());
                        info.setMaxPrice(line.get(4).toString());
                        info.setTradeAmount(line.get(5).toString());
                        list.add(info);
                   }
               }
                break;
            case "2":
                break;
            case "3":break;
            case "4":break;
            case "5":break;
            case "6":break;
            case "7":break;
            case "8":break;
            case "9":break;
        }
        return list;
    }

}

